package com.hjq.fcloud.ui.activity

import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.text.TextUtils
import android.widget.FrameLayout
import android.widget.LinearLayout
import com.hjq.base.BaseDialog
import com.hjq.fcloud.R
import com.hjq.fcloud.app.AppActivity
import com.hjq.fcloud.other.PermissionCallback
import com.hjq.fcloud.ui.dialog.MessageDialog
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.huawei.hms.hmsscankit.OnResultCallback
import com.huawei.hms.hmsscankit.RemoteView
import com.huawei.hms.ml.scan.HmsScan
import kotlinx.android.synthetic.main.activity_common_scan.frameLayout

/**
 * 公共扫码
 */
class CommonScanActivity : AppActivity() {

    companion object {
        val SCAN_RESULT = "scanResult"
    }

    var savedInstanceState: Bundle? = null

    private var remoteView: RemoteView? = null

    var mScreenWidth = 0
    var mScreenHeight = 0

    //The width and height of scan_view_finder is both 240 dp.
    val SCAN_FRAME_SIZE = 240

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.savedInstanceState = savedInstanceState
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_common_scan
    }

    override fun initView() {}

    override fun initData() {
        startScanQrCode()
    }


    fun startScanQrCode() {
        if (XXPermissions.isGranted(this, Permission.CAMERA)) {
            scan()
        } else {
            showScanQrCodeDialog(context, {
                scan()
            })
        }
    }

    private fun scan() {
        XXPermissions.with(this)
            .permission(Permission.CAMERA)
            .request(object : PermissionCallback() {
                override fun onGranted(
                    permissions: MutableList<String?>?,
                    all: Boolean
                ) {
                    if (all) {
                        performStartScan()
                    }
                }
            })
    }

    private fun showScanQrCodeDialog(context: Context, callBack: () -> Unit) {
        MessageDialog.Builder(context)
            .setMessage(getString(R.string.common_permission_title_camear)) // 确定按钮文本
            .setConfirm(context.resources.getString(R.string.common_web_location_permission_allow)) // 设置 null 表示不显示取消按钮
            .setCancel(context.resources.getString(R.string.common_web_location_permission_reject)) // 设置点击按钮后不关闭对话框
            .setListener(object : MessageDialog.OnListener {
                override fun onConfirm(dialog: BaseDialog?) {
                    callBack()
                }

                override fun onCancel(dialog: BaseDialog?) {
                    super.onCancel(dialog)
                    finish()
                }
            }).show()
    }

    private fun performStartScan() {
        initRemoteView()

        remoteView?.onStart()
    }


    private fun initRemoteView() {
        //1. Obtain the screen density to calculate the viewfinder's rectangle.
        val dm = resources.displayMetrics
        val density = dm.density
        //2. Obtain the screen size.
        mScreenWidth = resources.displayMetrics.widthPixels
        mScreenHeight = resources.displayMetrics.heightPixels

        val scanFrameSize: Int = (SCAN_FRAME_SIZE * density).toInt()
        //3. Calculate the viewfinder's rectangle, which in the middle of the layout.
        //Set the scanning area. (Optional. Rect can be null. If no settings are specified, it will be located in the middle of the layout.)
        val rect = Rect()
        rect.left = mScreenWidth / 2 - scanFrameSize / 2
        rect.right = mScreenWidth / 2 + scanFrameSize / 2
        rect.top = mScreenHeight / 2 - scanFrameSize / 2
        rect.bottom = mScreenHeight / 2 + scanFrameSize / 2

        //Initialize the RemoteView instance, and set callback for the scanning result.
        remoteView = RemoteView.Builder().setContext(this).setBoundingBox(rect)
            .setFormat(HmsScan.ALL_SCAN_TYPE).build()
        // Subscribe to the scanning result callback event.
        remoteView?.setOnResultCallback(OnResultCallback { result -> //Check the result.
            if (result != null && result.size > 0 && result[0] != null && !TextUtils.isEmpty(result[0].getOriginalValue())) {
                val intent = Intent()
                intent.putExtra(SCAN_RESULT, result[0])
                setResult(RESULT_OK, intent)
                finish()
            }
        })
        // Load the customized view to the activity.
        remoteView?.onCreate(savedInstanceState)
        val params = FrameLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT
        )
        frameLayout.addView(remoteView, params)
    }


    /**
     * Call the lifecycle management method of the remoteView activity.
     */
    override fun onStart() {
        super.onStart()
        remoteView?.onStart()
    }

    override fun onResume() {
        super.onResume()
        remoteView?.onResume()
    }

    override fun onPause() {
        super.onPause()
        remoteView?.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        remoteView?.onDestroy()
    }

    override fun onStop() {
        super.onStop()
        remoteView?.onStop()
    }

}